// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    motto: 'Hello World',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
  },
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },

   string_crc8: function(data) {
    let crc = 0x00;
    for (let i = 0; i < data.length; i++) {
        crc ^= data.charCodeAt(i);
        for (let j = 0; j < 8; j++) {
            if (crc & 0x80) {
                crc = (crc << 1) ^ 0x07; // 0x07 是 CRC-8-CCITT 的多项式
            } else {
                crc <<= 1;
            }
            crc &= 0xFF; // 确保 crc 保持在 8 位范围内
        }
    }
    return crc;
  },

  number_crc8: function(data) {
    let crc = 0x00;
    for (let i = 0; i < data.length; i++) {
        crc ^= data[i];
        for (let j = 0; j < 8; j++) {
            if (crc & 0x01) {
                crc = (crc >> 1) ^ 0x8C; // 0x07 是 CRC-8-CCITT 的多项式
            } else {
                crc >>= 1;
            }
            crc &= 0xFF; // 确保 crc 保持在 8 位范围内
        }
    }
    return crc;
  },

  single_crc8:function(crc, data){
    crc ^= data;
    for (let j = 0; j < 8; j++) {
        if (crc & 0x01) {
            crc = (crc >> 1) ^ 0x8C; // 0x07 是 CRC-8-CCITT 的多项式
        } else {
            crc >>= 1;
        }
        crc &= 0xFF; // 确保 crc 保持在 8 位范围内
    }
    return crc;
  },

  xor_update_buf: function(result, arr){
    if(arr.length === 0){
      throw new Error("数组不能为空");
    }

    for(let i = 0; i<arr.length; i++)
    {
      result ^= arr[i];
    }

    return result;
  },

  LONIB:function(X){
    return (X & 0x0f);
  },

  HINIB:function(X){
    return (this.LONIB(X >> 4));
  },

  MKBYTE:function(H, L){
    return ((H << 4) | (L & 0x0f));
  },

  MKINT16:function(H, L){
    return ((H << 8) | (L & 0xff));
  },

  tricode:function(data, index, tricode, n, comment){
    let crc = 0;
    crc = this.single_crc8(crc, data);
    console.log("data is "+ data + ", crc data:" + crc);
    crc = this.single_crc8(crc, index);
    console.log("crc index:" + crc);

    tricode[n] = this.MKINT16(0x00, this.MKBYTE(this.HINIB(crc), this.HINIB(data)));
    let temp_value = this.MKBYTE(this.HINIB(crc), this.HINIB(data));
    console.log(`${temp_value}, ${this.HINIB(crc)} ,${this.HINIB(data)}`);
    tricode[n+1] = this.MKINT16(0x01, index);
    tricode[n+2] = this.MKINT16(0x00, this.MKBYTE(this.LONIB(crc), this.LONIB(data)));

    console.log("TriCode: data=" + data + ",index="+index + ",comment=" + comment + " -> " + `tricode[${n}]=${tricode[n].toString(16)}, tricode[${n+1}]=${tricode[n+1].toString(16)}, tricode[${n+2}]=${tricode[n+2].toString(16)}`);

    return 3;
  },

  initWifi: function () {
    // 检查 WiFi 模块是否初始化
    wx.startWifi({
      success: (res) => {
        console.log('WiFi 模块初始化成功');
        // 获取 WiFi 列表
        this.getWifiList();
      },
      fail: (err) => {
        console.error('WiFi 模块初始化失败', err);
      }
    });
  },

  getWifiInfo: function(){
    wx.getConnectedWifi({
      success: (res) => {
        console.log('getConnectedWifi info 成功');
        console.log(`ssid:${res.wifi.SSID},bssid:${res.wifi.BSSID}`);
      },
      fail: (err) => {
        console.error('获取已连接WiFi信息失败', err);
        // 这里可以添加错误处理逻辑，如提示用户检查WiFi设置等
      }
    })
  },

  initWifi: function () {
    // 检查 WiFi 模块是否初始化
    wx.startWifi({
      success: (res) => {
        console.log('WiFi 模块初始化成功');
        // 获取 WiFi 列表
        this.getWifiInfo();
      },
      fail: (err) => {
        console.error('WiFi 模块初始化失败', err);
      }
    });
  },

  onLoad: function(){
    this.initWifi();
    //ssid
    const ssid = "IoT_Test";
    console.log('ssid is:'+ssid);
    const arr = ssid.split("");
    console.log(arr);
    const ssidNumber = arr.map(letter => letter.charCodeAt(0));
    console.log(ssidNumber);

    //passwd
    const APpasswd = "Asdf123456"
    console.log("passwd: " + APpasswd + ", length is " + APpasswd.length);
    const Passwordarr = APpasswd.split("");
    console.log(Passwordarr);
    const passwordNumber = Passwordarr.map(letter => letter.charCodeAt(0));
    console.log(passwordNumber);

    //mac地址 bssid
    const MacAddress = "00:1A:2B:3C:4D:5E";
    const MacArray = MacAddress.split(":");
    console.log(MacArray);
    const MacArrayNum = MacArray.map(string => parseInt(string, 16));
    let bssid_len = MacArrayNum.length;
    console.log(MacArrayNum);

    //ip
    const ipAddress = "192.168.148.129";
    const ipArray = ipAddress.split(".");
    console.log(ipArray);
    const ipArrayNum = ipArray.map(string => Number(string));
    let ip_len = ipArrayNum.length;
    console.log(ipArrayNum);

    let ssid_len = ssidNumber.length;
    let ssid_crc = this.number_crc8(ssidNumber);
    console.log('ssid length: ' + ssid_len +', ssid number crc:'+ ssid_crc);

    let bssid_crc = this.number_crc8(MacArrayNum);
    console.log('bssid number crc:'+ bssid_crc);
    let password_len = APpasswd.length;

    let total_len = 0;
    total_len = 1 + 1 + 1 + 1 + 1 + 4 + password_len + ssid_len;
    total_len %= 256;
    console.log("total_len is " + total_len);

    let total_xor = 0;
    total_xor ^= total_len;
    total_xor ^= password_len;
    total_xor ^= ssid_crc;
    total_xor ^= bssid_crc;
    console.log("total_xor1 result: " + total_xor);
    total_xor = this.xor_update_buf(total_xor, ipArrayNum);
    console.log("total_xor2 result: " + total_xor);
    total_xor = this.xor_update_buf(total_xor, passwordNumber);
    console.log("total_xor3 result: " + total_xor);
    total_xor = this.xor_update_buf(total_xor, ssidNumber);
    console.log("total_xor result: " + total_xor);

    let length = 105;
    let datumcode = Array.from({ length: length }, () => 0); // 初始化元素为0
    console.log(datumcode); // [0, 0, 0, 0, 0]

    let n = 0;
    let t = 0;
    n += this.tricode(total_len,  t++, datumcode, n,"total_len");  
    n += this.tricode(password_len, t++, datumcode, n, "passwd_len"); 
    n += this.tricode(ssid_crc,  t++, datumcode, n, "essid_crc"); 
    n += this.tricode(bssid_crc,  t++, datumcode, n, "bssid_crc");  
    n += this.tricode(total_xor,  t++, datumcode, n, "total_xor"); 

    for (let i=0; i<ip_len; i++)
    {
      n += this.tricode(ipArrayNum[i], t++, datumcode , n, "ipaddr");
    }
    
    for (let i=0; i<password_len; i++)
    {
      n += this.tricode(passwordNumber[i], t++, datumcode , n, "ap_pwd");
    }
  
    for (let i=0; i<bssid_len; i++)
    {
      n += this.tricode(MacArrayNum[i], t++, datumcode , n, "bssid");
    }
    console.log(`dcode_len = ${n}`);

  },
})
